<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="container"></div>
    <script>
      function vortex(n, m) {
        const nums = new Array(n).fill(0).map(() => new Array(m).fill(0));
        let i = 0,
          j = 0,
          stepi = 1,
          stepj = 0,
          count = 1;
        function isTurn() {
          return !nums[j] || nums[j][i] !== 0;
        }
        while (1) {
          nums[j][i] = count++;
          i += stepi;
          j += stepj;
          if (isTurn()) {
            i -= stepi;
            j -= stepj;
            if (stepj === 0) {
              stepj = stepi;
              stepi = 0;
            } else {
              stepi = -stepj;
              stepj = 0;
            }
            i += stepi;
            j += stepj;
          }
          // 转向后也没有路就退出循环
          if (isTurn()) {
            break;
          }
        }
        return nums;
      }

      const n = 5;
      const m = 6;
      const result = vortex(n, m);

      const dom = document.getElementById("container");

      // 在dom 创建n*m的div，填充result数组
      for (let i = 0; i < n; i++) {
        const row = document.createElement("div");
        row.className = "row";
        for (let j = 0; j < m; j++) {
          const cell = document.createElement("div");
          cell.className = "col";
          cell.textContent = result[i][j] || "";
          row.appendChild(cell);
        }
        dom.appendChild(row);
      }
    </script>

    <style>
      #container {
        margin: 100px auto;
        width: 250px;
        border: 1px solid #ccc;
      }
      .row {
        display: inline-block;
      }
      .col {
        box-sizing: border-box;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        border: 1px solid #ccc;
      }
    </style>
  </body>
</html>
